#!/usr/bin/python2.5
#
# (c) 2009 - Chip Turner
#
# Apache License, blah blah, it's a few hundred lines of python.

import logging
import os
import time
import sys
import datetime
import optparse
import textwrap
import feedparser
import collections
import PyRSS2Gen
import pytz.reference

import armory_lib


def EntryItemSorter(a, b):
  return cmp(a[1].published_parsed, b[1].published_parsed)

def main(args):
  parser = optparse.OptionParser(__doc__)
  parser.add_option("-r", "--realm", help="realm player or guild is on")
  parser.add_option("-g", "--guild", help="guild players are a member of")
  parser.add_option("", "--match", help="string in the feed activity to match")
  parser.add_option("", "--eu", help="Use EU Armory instead of US armory",
                    action="store_true")
  parser.add_option("-p", "--players", help="players to query")
  parser.add_option("-v", "--verbose", help="show debugging output", action="store_true")
  parser.add_option("-l", "--level", help="minimum level to show results for", type=int, default=80)
  parser.add_option("-x", "--exclude", help="exclude this user", action="append")
  parser.add_option("", "--exclude-file", help="path to file containing names to exclude, one per line")
  parser.add_option("-m", "--maxrank", help="maximum rank to show results for (numeric, gm=0)",
                    type=int)

  options, args = parser.parse_args(args)
  assert options.guild and options.realm

  if options.verbose:
    armory_lib.InitLogging(logging.DEBUG)
  else:
    armory_lib.InitLogging()

  if options.eu:
    armory_interface = armory_lib.ArmoryInterface("eu")
  else:
    armory_interface = armory_lib.ArmoryInterface("us")

  members = armory_interface.ParseRoster(options.realm, options.guild)
  day_items = collections.defaultdict(list)
  exclude = options.exclude or []
  if options.exclude_file:
    exclude.extend(l.strip() for l in open(options.exclude_file, "r").readlines())

  items_received = list()
  for name, level, race_id, class_id, rank in members:
    if level < options.level: continue
    if options.maxrank and rank > options.maxrank: continue
    if name in exclude: continue
    feed = feedparser.parse("http://www.wowarmory.com/character-feed.atom?r=%s&cn=%s" % (options.realm, name))
    for entry in feed.entries:
      if not options.match or entry.title.lower().find(options.match.lower()) >= 0:
        print "%s - %s" % (name.decode('utf-8'), entry.title.decode('utf-8'))
        items_received.append((name, entry))
        utc_dt = datetime.datetime(*entry.published_parsed[0:6])
        pst_dt = utc_dt + pytz.reference.Pacific.utcoffset(utc_dt)
        print pst_dt
        pst_day = datetime.datetime(pst_dt.year, pst_dt.month, pst_dt.day)
        day_items[pst_day].append((name, entry))

  items_received.sort(EntryItemSorter)
  items = list()
  for day in sorted(day_items):
    print "%s:" % day
    if not day_items[day]: continue
    loot_items = list()
    for player, entry in day_items[day]:
      print "  %s: %s - %s" % (entry.published, player.decode('utf-8'), entry.title.decode('utf-8'))
      loot_string = entry.content[0].value
      loot_items.append("%s: %s" % (player.decode('utf-8'), loot_string))
    description = "<ul><li>" + "</li><li>".join(loot_items) + "</li></ul>"
    items.append(PyRSS2Gen.RSSItem(title=u"Loot for %s" % (day),
                                   description=description,
                                   pubDate=day))

  
  rss = PyRSS2Gen.RSS2(title="Items looted by %s" % options.guild,
                       link="http://www.wowarmory.com/guild-info.xml?r=%s&n=%s" % (options.realm, options.guild),
                       description="Recently looted items by %s" % options.realm,
                       lastBuildDate=datetime.datetime.now(),
                       items=items)
  rss.write_xml(open("%s.xml" % options.guild, "w"))

if __name__ == '__main__':
  main(sys.argv[1:])
